package com.zlx.controller;


import com.zlx.entities.User;
import com.zlx.service.UserService;
import com.zlx.utils.Page;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.List;
import java.util.Map;

@WebServlet("/user/*")
public class UserServlet extends HttpServlet {
    private UserService service = new UserService();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        String uri = req.getRequestURI();
        String[] split = uri.split("/");
        if ("login".equals(split[split.length - 1])) {
            login(req, resp);
        } else if ("list".equals(split[split.length - 1])) {
            list(req, resp);
        } else if ("add".equals(split[split.length - 1])) {
            add(req, resp);
        } else if ("delete".equals(split[split.length - 1])) {
            delete(req, resp);
        } else if ("toEdit".equals(split[split.length - 1])) {
            toEdit(req, resp);
        } else if ("update".equals(split[split.length - 1])) {
            update(req, resp);
        }
    }

    //登陆
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        String name = null;
        String password = null;
        //获取request域的信息
        Cookie[] cookies = req.getCookies();
//            System.out.println("sys");
        if (cookies.length > 0 && cookies != null) {
            for (Cookie cookie : cookies) {
                //判断是否有用户名或密码的cookie
                if ("username".equals(cookie.getName())) {
                    name = cookie.getValue();
                } else if ("password".equals(cookie.getName())) {
                    password = cookie.getValue();
                }
//                    System.out.println(name + ":" + password);
            }
        }
        if (name == null && password == null) {//request域的信息没有就会去取信息
            name = req.getParameter("name");
            password = req.getParameter("password");
        }
        User user = service.checkUserExist(name, password);
        if (user == null) {
            //登录失败
            req.setAttribute("error", "用户名或密码错误，请重新输入！");
            req.getRequestDispatcher("/index.jsp").forward(req, resp);
        } else {
            //登陆成功
            HttpSession session = req.getSession();
            //添加信息到session域
            session.setAttribute("user", user);
           /* //设置cookie
            Cookie username = new Cookie("username", user.getName());
            Cookie upassword = new Cookie("password", user.getPassword());
            //设置cookie的时间
            username.setMaxAge(60 * 60 * 24 * 3);
            upassword.setMaxAge(60 * 60 * 24 * 3);
            resp.addCookie(username);
            resp.addCookie(upassword);*/
//            req.getRequestDispatcher("/user/list").forward(req,resp);
            resp.sendRedirect("/user/list");
        }
    }

    //查用户列表
    protected void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        //获取模糊查询数据
//        String name = new String(req.getParameter("name").getBytes("ISO8859-1"),"UTF-8");
        String name = req.getParameter("name");
        if (name == null) {
            name = "";
        }
        //获取当前页
        String currentPage = req.getParameter("currentPage");
        if (currentPage == null || "".equals(currentPage)) {
            currentPage = "1";
        }
        Page<User> page = new Page<>(service.getUserCount(name), null, null, Integer.valueOf(currentPage));
        List<User> list = service.getList(page, name);
        page.setItems(list);
        req.setAttribute("page", page);
        req.setAttribute("name", name);
        req.getRequestDispatcher("/list.jsp").forward(req, resp);
    }

    //添加用户
    protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        //获取数据集合
        Map parameterMap = req.getParameterMap();
        User user = new User();
        try {
            //调用BeanUtils工具对数据封装到user
            BeanUtils.populate(user, parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
//        System.out.println(user);
        service.createUser(user);
        resp.sendRedirect("/user/list");
    }

    //删除用户
    protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        String id = req.getParameter("id");
        String currentPage = req.getParameter("currentPage");
        String name = req.getParameter("name");
        service.deleteUserById(Integer.valueOf(id));
        req.setAttribute("currentPage", currentPage);
        req.setAttribute("name", name);
        req.getRequestDispatcher("/user/list").forward(req, resp);
//        resp.sendRedirect("/user/list?currentPage="+currentPage+"&name="+name);
    }

    //回显编辑数据
    protected void toEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        User user = service.getUserById(Integer.valueOf(id));
        req.setAttribute("user", user);
        req.getRequestDispatcher("/edit.jsp").forward(req, resp);
    }

    //根据id更新客户
    protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        //获取数据集合
        Map parameterMap = req.getParameterMap();
        User user = new User();
        try {
            //调用BeanUtils工具对数据封装到user
            BeanUtils.populate(user, parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        service.updateUserById(user);
        //重定向到用户列表
        resp.sendRedirect("/user/list");
    }
}
